#include "ls_config_file.h"
#include "ls_little_fs.h"


#define DBG_TAG "CONFIG"
#include "ls_trace_common.h"
#include "ls_file_common.h"


#pragma pack(1)
typedef  struct 
{
    char  initd;
    
    union 
    {
        struct device
        {
            char SN[24];
        }device;
        char device_data[128];
    };
    

    

    //wifi配置
    union
    {
        struct wifi
        {
            char  initd;
            char  ssid[63];
            char  passwd[64];
        }wifi;
        char wifi_data[256];
    };


}LS_CONFIG_FILE_S;

#pragma pack()

static  LS_CONFIG_FILE_S config_file;


#define DEVICE_CONFIG_FILE "deviceInfo.conf"


static void __ls_config_writeDeviceInfo(LS_CONFIG_FILE_S *_ConfigInfo)
{
    LS_FILE_COMMON_WriteBufInFile(DEVICE_CONFIG_FILE,&_ConfigInfo->device, sizeof(_ConfigInfo->device));
}


/// @brief 
/// @param _ConfigInfo 
static void __ls_config_readDeviceInfo(LS_CONFIG_FILE_S *_ConfigInfo)
{
    struct device devInfo;

    struct lfs_info info={0};
    int ret = lfs_stat(ls_get_fs_config(),DEVICE_CONFIG_FILE,&info);
    if(!(info.size > 0))
    {
        LS_TRACE_ERROR("device info not find");
    }
    else
    {
        LS_FILE_COMMON_ReadFileInBuf(DEVICE_CONFIG_FILE,_ConfigInfo->device_data,sizeof(_ConfigInfo->device_data));
    }
}
/**************************************/
#define DEVICE_CONFIG_FILE "wifi.conf"



/// @brief 
/// @param _ConfigInfo 
static void __ls_config_writeWifiInfo(LS_CONFIG_FILE_S *_ConfigInfo)
{
    LS_FILE_COMMON_WriteBufInFile(DEVICE_CONFIG_FILE,&_ConfigInfo->wifi,sizeof(_ConfigInfo->wifi));
}



/// @brief 
/// @param _ConfigInfo 
static void __ls_config_readWifiInfo(LS_CONFIG_FILE_S *_ConfigInfo)
{

    struct lfs_info info={0};
    int ret = lfs_stat(ls_get_fs_config(),DEVICE_CONFIG_FILE,&info);
    if(!(info.size > 0))
    {
        LS_TRACE_ERROR("not find %s",DEVICE_CONFIG_FILE);
    }
    else
    {
        LS_FILE_COMMON_ReadFileInBuf(DEVICE_CONFIG_FILE,&_ConfigInfo->wifi,sizeof(_ConfigInfo->wifi));
    }

}


 
/// @brief 配置文件初始化，最后得512作为配置文件和LOG
/// @return 
int ls_config_file_init()
{
    //设备信息
   __ls_config_readDeviceInfo(&config_file);

   //wifi info
    __ls_config_readWifiInfo(&config_file);
   return 0;
}




/// @brief 
/// @return 
int ls_config_get_wifi(char ssid[64],char passwd[64])
{
    int ret = -1;
    if(config_file.wifi.initd == 1)
    {
        if(ssid)
        snprintf(ssid,64,"%s",config_file.wifi.ssid);
        if(passwd)
        snprintf(passwd,64,"%s",config_file.wifi.passwd);
        ret = 0;
    }
    return ret;
}


/// @brief 
/// @param ssid 
/// @param passwd 
/// @return 
int ls_config_set_wifi(const char ssid[64],const char passwd[64])
{
    config_file.wifi.initd = 1;
    snprintf(config_file.wifi.ssid,64,"%s",ssid);
    snprintf(config_file.wifi.passwd,64,"%s",passwd);
    __ls_config_writeWifiInfo(&config_file);
    return 0;
}